package com.app.controller.backstage;

import cn.hutool.core.util.StrUtil;
import com.app.enums.StatusCodeEnum;
import com.app.mapper.*;
import com.app.model.*;
import com.app.service.JobPublishService;
import com.app.util.LiExcelHelperUtils;
import com.app.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/adminUpload")
@Slf4j
public class AdminUploadController {

    @Autowired
    private JobPublishService jobPublishService;
    @Qualifier("jobPublishMapper")
    @Autowired
    private JobPublishMapper jobPublishMapper;
    @Autowired
    private EnterpriseMapper enterpriseMapper;
    @Qualifier("comRecruitersMapper")
    @Autowired
    private ComRecruitersMapper comRecruitersMapper;
    @Autowired
    private PersonalInformationMapper personalInformationMapper;
    @Autowired
    private PositionMapper positionMapper;

    @ApiOperation(value = "下载导入模板文件")
    @GetMapping("/downloadImportTemplateFile")
    public Result downloadImportTemplateFile(HttpServletResponse response, String fileName) throws Exception {
        // 定义文件路径
//        String filePath = System.getProperty("user.dir") + "/template/招聘岗位导入模板.xlsx";
        return Result.success("/template/招聘岗位导入模板.xlsx");
    }


    @ApiOperation(value = "导入模板文件")
    @PostMapping("/importTemplateFile")
    public Result importTemplateFileTest(HttpServletRequest request,
                                         @RequestParam("file") MultipartFile mfile) throws Exception {
//        String token = request.getHeader("token");
//        if (token == null) {
//            return Result.error(400,"请登录");
//        }
        List<EnterpriseModel> list1 = enterpriseMapper.selectList(new QueryWrapper<EnterpriseModel>());
        List<PositionModel> positionModels = positionMapper.selectList(new QueryWrapper<PositionModel>());
        Map<String, Integer> positionModelsMap = positionModels.stream()
                .distinct() // 需要根据具体的去重条件自定义
                .collect(Collectors.toMap(PositionModel::getJobTitle, PositionModel::getId,   (existing, replacement) -> existing));
        Map<String, Integer> stringIntegerMap = list1.stream()
                .collect(Collectors.toMap(
                        EnterpriseModel::getEnterpriseName,
                        EnterpriseModel::getId,
                        (existing, replacement) -> existing // 或者使用 replacement 以保留第二个值
                ));
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        List<String[]> list = LiExcelHelperUtils.readExcelToStringArray(mfile, 1);


        int validRows = 0; // 用于跟踪有效数据行的数量
        List<JobPublishModel> jobPublishList = new ArrayList<>();
        Set<String> accountSet = new HashSet<>();
        Set<String> gasNumberSet = new HashSet<>();
        List<String> errorList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            String[] str = list.get(i);
            if (str.length < 12) {
                return Result.error(400, "请下载导入模板编辑后再上传!");
            }
            String jobTitle = str[0].trim();
            Integer expIdStr = 1;
            Integer eduIdStr = 1;
            String minSalaryStr = str[1].trim();
            String maxSalaryStr = str[2].trim();
            String jobDescription = str[3].trim();
            String jobAddress = str[4].trim();
            String companyName = str[5].trim();
            String startTime = str[6].trim();
            String endTime = str[7].trim();
            String officeAsk = str[8].trim();
            String salaryNegotiableStr = str[9].trim();
            String jobNumberStr = str[10].trim();
            String jobType = str[11].trim();


            // 打印每个参数的值
            System.out.println("jobTitle: " + jobTitle);
            System.out.println("minSalaryStr: " + minSalaryStr);
            System.out.println("maxSalaryStr: " + maxSalaryStr);
            System.out.println("jobDescription: " + jobDescription);
            System.out.println("jobAddress: " + jobAddress);
            System.out.println("companyName: " + companyName);
            System.out.println("startTime: " + startTime);
            System.out.println("endTime: " + endTime);
            System.out.println("officeAsk: " + officeAsk);
            System.out.println("salaryNegotiableStr: " + salaryNegotiableStr);
            System.out.println("jobNumberStr: " + jobNumberStr);
            System.out.println("jobType: " + jobType);

            if (0 == i) {
                if (!"工作名称".equals(jobTitle) || !"最低薪资".equals(minSalaryStr) || !"最高薪资".equals(maxSalaryStr) || !"工作描述".equals(jobDescription)
                        || !"工作地点".equals(jobAddress) || !"公司名称".equals(companyName) || !"上班时间".equals(startTime) || !"下班时间".equals(endTime) ||
                        !"任职要求".equals(officeAsk) || !"福利待遇".equals(salaryNegotiableStr) || !"岗位需求人数".equals(jobNumberStr) ||!"行业".equals(jobType)) {
                    return Result.error(400, "请下载导入模板编辑后再上传!");
                }
            } else {
                if (jobTitle.contains("备注")) {
                    break;
                }
                // 所有数据为空，则无数据，跳出当前循环
                if (StringUtils.isBlank(jobTitle)
                        && StringUtils.isBlank(minSalaryStr)
                        && StringUtils.isBlank(maxSalaryStr)
                        && StringUtils.isBlank(jobDescription)
                        && StringUtils.isBlank(jobAddress)
                        && StringUtils.isBlank(companyName)
                        && StringUtils.isBlank(startTime)
                        && StringUtils.isBlank(endTime)
                        && StringUtils.isBlank(officeAsk)
                        && StringUtils.isBlank(salaryNegotiableStr)
                        && StringUtils.isBlank(jobType)
                        && StringUtils.isBlank(jobNumberStr)) {
                    break; // 如果所有字段都是空字符串或空白字符，则跳出循环
                }

// 如果当前行不是全部为空，则视为有效数据行
                boolean isAllEmpty = StringUtils.isBlank(jobTitle)
                        && StringUtils.isBlank(minSalaryStr)
                        && StringUtils.isBlank(maxSalaryStr)
                        && StringUtils.isBlank(jobDescription)
                        && StringUtils.isBlank(jobAddress)
                        && StringUtils.isBlank(companyName)
                        && StringUtils.isBlank(startTime)
                        && StringUtils.isBlank(endTime)
                        && StringUtils.isBlank(officeAsk)
                        && StringUtils.isBlank(jobType)
                        && StringUtils.isBlank(salaryNegotiableStr)
                        && StringUtils.isBlank(jobNumberStr);

                JobPublishModel jobPublish = new JobPublishModel();
                jobPublish.setJobTitle(jobTitle);

                jobPublish.setExpId(expIdStr);
                jobPublish.setEduId(eduIdStr);
                jobPublish.setMinSalary(Integer.parseInt(minSalaryStr));
                jobPublish.setMaxSalary(Integer.parseInt(maxSalaryStr));
                jobPublish.setJobDescription(jobDescription);
                jobPublish.setJobAddress(jobAddress);
                jobPublish.setRecruitType(1);
                jobPublish.setStartTime(startTime);
                jobPublish.setEndTime(endTime);
                jobPublish.setRecruitState(3); //1审核未通过   2待审核  3审核通过  4关闭
                jobPublish.setOfficeAsk(officeAsk);
                jobPublish.setSalaryNegotiable(0);
                jobPublish.setCrtTime(new Timestamp(System.currentTimeMillis()));
                jobPublish.setWorry(0);
                jobPublish.setWelfare(salaryNegotiableStr);
                jobPublish.setJobNumber(Integer.parseInt(jobNumberStr));
                jobPublish.setAddressType(1);
                jobPublish.setModelType(1);
                jobPublish.setIsDelete(0); // 默认不删除


                try {
                    Integer jobTypeValue = positionModelsMap.entrySet().stream()
                            .filter(entry -> entry.getKey().contains(jobType)) // 模糊匹配
                            .map(Map.Entry::getValue)
                            .findFirst() // 找到第一个匹配的值
                            .orElse(4199); // 如果没有找到，则使用默认值

                    jobPublish.setJobType(jobTypeValue);
                    Optional<Integer> value = stringIntegerMap.entrySet().stream()
                            .filter(entry -> entry.getKey().contains(companyName))
                            .map(Map.Entry::getValue)
                            .findFirst(); // 获取第一个匹配的值
                    jobPublish.setEnrollId(value.get()); // 根据公司名称获取 ID
                    jobPublishList.add(jobPublish);
                    validRows++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        // 批量插入数据
        if(jobPublishList!=null && jobPublishList.size()>0){
            jobPublishMapper.saveBatch(jobPublishList);
        }
        return Result.success("导入成功! 有效数据行数: " + validRows);
    }


}
